//
//  QFHomeViewController.swift
//  sinaWeibo
//
//  Created by apple on 16/2/26.
//  Copyright © 2016年 Qifeng Yan. All rights reserved.
//

import UIKit

class QFHomeViewController: QFBaseTableViewController {

    // MARK: - 属性
    var statuses: [QFStatus]? {
        didSet{
            self.tableView.reloadData() // 刷新数据  在给模型赋值的时候
        }
    }
    
    private let identifier = "cellID"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !QFUserAccountViewModel.sharedInstance.isUserLogin {
            return
        }
        
        setupBarButtonItem()
        
        loadStatus()
        
        // 注册cell
        tableView.registerClass(QFStatusCell.self, forCellReuseIdentifier: identifier)
        
        tableView.estimatedRowHeight = 150
        tableView.rowHeight = UITableViewAutomaticDimension
    }
    
    
    
    /// 加载微博数据
    private func loadStatus() {
//        QFNetworkTool.sharedInstance.loadStatus { (result, error) -> () in
//            self.statusVM.loadStatuses() 
//        }
        statusVM.loadStatuses { (status, error) -> () in
            if error != nil {
                print("加载模型失败")
                return
            }
            
//            print("在控制器中打印： \(status)")
            self.statuses = status
        }
    }
    
    /// 设置导航栏
    private func setupBarButtonItem() {
        setupLeftAndRightButtonItem()
        setupTitleButton()
    }

    /// 设置左右两边的按钮
    private func setupLeftAndRightButtonItem() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
        
    }
    
    
    
    /// 设置标题
    private func setupTitleButton() {
        let titleButton = QFHomeTitleButton(title: "我是标题")
        
        // 添加点击事件
        titleButton.addTarget(self, action: "titleButtonDidClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        navigationItem.titleView = titleButton
    }
    
    
    /// 监听按钮的点击事件
    func titleButtonDidClick(button: UIButton) {
        button.selected = !button.selected
        
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            button.imageView!.transform = button.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI) - 0.001) : CGAffineTransformIdentity
        })
        
        // 点击按钮弹出popover
        if button.selected {
            let popoverVC = QFPopoverViewController()
            
            // 设置popover样式
            popoverVC.modalPresentationStyle = UIModalPresentationStyle.Popover
            popoverVC.popoverPresentationController?.sourceView = navigationItem.titleView  // popover参照哪一个view
            popoverVC.popoverPresentationController?.sourceRect = navigationItem.titleView!.bounds  // popover 从哪个方向出来 不写 默认是从参照view的0位点
            popoverVC.popoverPresentationController?.delegate = self // 设置代理
            
            // 设置 modal出来的view的大小
            popoverVC.preferredContentSize = CGSize(width: 200, height: 5 * 44)
            
            // modal 到popover 控制器
            presentViewController(popoverVC, animated: true, completion: nil)
        }
        
    }
    
    // MARK: - 懒加载用户模型ViewModel
    private let statusVM: QFStatusViewModel = QFStatusViewModel()
}

// MARK: - tableView 数据源方法
extension QFHomeViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as! QFStatusCell
        
//        cell.textLabel?.text = statuses?[indexPath.row].text
        cell.status = statuses?[indexPath.row]
        
        return cell
        
    }
    
    
    
    
}

// MARK: - UIPopoverPresentationControllerDelegate 代理方法
extension QFHomeViewController:UIPopoverPresentationControllerDelegate {
    // 显示popover 样式 调用 这个方法
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.None
    }
    
    // 当popover 消失后调用这个方法
    func popoverPresentationControllerDidDismissPopover(popoverPresentationController: UIPopoverPresentationController) {
        // 获取titButton
        let button = navigationItem.titleView as! QFHomeTitleButton
        
        // 调用按钮的点击方法 在popover消失的时候 箭头旋转下来
        titleButtonDidClick(button)
    }
}
